using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Player : MonoBehaviour
{
    public float moveSpeed = 5f;  // 移动速度
    public float jumpForce = 10f;  // 弹跳速度
    public float dashSpeed = 10f; // 冲刺速度
    public float dashDuration = 0.2f; // 冲刺持续时间
    private Vector2 currentVelocity = Vector2.zero; // 用于平滑速度变化
    public float dashSmoothTime = 0.3f; // 冲刺结束后的平滑恢复时间
    public float JumptakeDamage = 10f; //冲刺一次减少的体力

    private Vector2 moveDirection;
    private bool isDashing = false;
    private Vector2 dashDirection;
    private float dashTime;

    public float gravity = -9.8f;  // 重力加速度
    private Rigidbody2D rb;
    public bool canUP;
    public bool canStartUp;
    public bool chongci;
    public float maxFallSpeed =3f;
    public float scalingMovingSpeed = 5f;

    public float maxHealth = 100f;  // 最大体力值
    public float currentHealth;     // 当前体力值
    public Image healthSlider;     // 用来显示体力的 Slider UI
    public Text healthText;         // 显示体力值的 Text
    public float healthRegenRate = 1f; // 每秒恢复体力的量
    public float dashHealthDrain = 1f; // 冲刺期间每秒减少的生命值
    
    private float damageCooldown = 0f;  // 扣除伤害的倒计时

    public bool canChange;
    public bool canChangeBig = false;  // 是否放大
    public bool canChangeSmall = false;  // 是否缩小
    public bool canChangeOri = false;


    public GameObject arrow;  // 箭头图片的GameObject
    public Transform startPoint;  // 箭头的起始点（可以是玩家或固定物体）
    public float displayTime = 10000000000f;  // 显示箭头的时间

    public float scaleSpeed = 0.1f; // 膨胀速度
    public float targetScaleMultiplier = 20f; // 目标放大倍数
    public float targetScaleSmall = 0.3f; // 目标缩小倍数
    private Vector3 originalScale; // 初始大小
    private Vector3 targetScale; // 目标大小
    private Vector3 smallScale; //目标缩小大小


    bool isScalingBig = false;
    bool isScalingSmall = false;

    public GameObject StaminaBar;
    public GameObject man;
    public GameObject kong;
    public ChangeState changeState;

    void Start()
    {
       

        canChange = true;
        originalScale = transform.localScale;  // 原始尺寸
        targetScale = originalScale * targetScaleMultiplier; // 计算目标大小
        smallScale = originalScale * targetScaleSmall;

        canUP = true;
        canStartUp = true;
        rb = GetComponent<Rigidbody2D>();
        rb.gravityScale = 0; // 设置重力为0

        currentHealth = maxHealth;  // 初始体力

        // ��ʼ�� Slider
        if (healthSlider != null)
        {
            healthSlider.fillAmount = 1;
            //healthSlider.value = currentHealth;  // 滚动条值匹配
        }

        // ��ʼ���ı�
        if (healthText != null)
        {
            healthText.text = "Health: " + currentHealth.ToString();
        }
    }

    void FixedUpdate()
    {
        
        if (isDashing)
        {
            
            // 执行冲刺
            dashTime += Time.fixedDeltaTime;
            rb.velocity = dashDirection * dashSpeed;

            // 冲刺时间到达后，停止冲刺
            if (dashTime >= dashDuration)
            {
                isDashing = false;
                rb.velocity = moveDirection * moveSpeed;
            }
        }
        else
        {
            // 平滑过渡到普通移动
            rb.velocity = Vector2.SmoothDamp(rb.velocity, new Vector2(moveDirection.x * moveSpeed, rb.velocity.y), ref currentVelocity, dashSmoothTime);
        }
    
    }
    void Update()
    {

        
        ShowArrow();
        if (chongci == false)
        {
            // 每秒恢复一定量的体力，确保不超过最大体力
            RegenerateHealth();
        }
        
        if(currentHealth - JumptakeDamage < 0 && canStartUp)
        {
            canUP = false;
        }
        if(currentHealth - JumptakeDamage > 0 && canStartUp )
        {
            canUP = true;
        }
        if (Input.GetKey(KeyCode.E))
        {
            chongci = true;           
        }
        else
        {
            chongci = false;
        }
        if (currentHealth - 1 < 0)
        {
            chongci = false;
        }

        MovePlayer();
        //CheckGroundStatus();
        if ((canChangeBig || Input.GetKey(KeyCode.Z)))
        {
            ApplyCustomGravity();
        }
        

        // UI更新
        if (healthSlider != null)
        {
            healthSlider.fillAmount = (float)currentHealth / maxHealth; // ��������������ʾ
        }

        if (healthText != null)
        {
            healthText.text = "Health: " + Mathf.Floor(currentHealth).ToString(); // ���������ı�
        }

        if (canChange)
        {
            // 变大
            if ((canChangeBig || Input.GetKey(KeyCode.Z)) )
            {
                isScalingBig = true;
                StartCoroutine(ScaleOverTime());
            }
            if (!canChangeBig && !Input.GetKey(KeyCode.Z))
            {
                isScalingBig = false;
                StopCoroutine(ScaleOverTime());
            }

            // X变小
            if ((canChangeSmall || Input.GetKey(KeyCode.X)) )
            {
                isScalingSmall = true;
                StartCoroutine(ScaleSmallTime());
            }
            if (!canChangeSmall && !Input.GetKey(KeyCode.X) )
            {
                isScalingSmall = false;
                StopCoroutine(ScaleSmallTime());
            }

            // C还原
            if (canChangeOri ||  Input.GetKeyDown(KeyCode.C))
            {
                StartCoroutine(ScaleHeat());
            }
            if (!canChangeSmall && !Input.GetKey(KeyCode.C))
            {
                StopCoroutine(ScaleHeat());
            }

        }
        if (chongci)
        {
            damageCooldown += Time.deltaTime; // 增加时间计数器

            // 开始逐渐扣除生命值
            StartTakingDamage(dashHealthDrain);
        }
        if(changeState.Extra ==true)
        {
            man.SetActive(false);
            kong.SetActive(false);
            healthRegenRate = 100;

        }
        if (changeState.Extra == false)
        {
            man.SetActive(true);
            kong.SetActive(true);
            healthRegenRate = 4;

        }

    }
    IEnumerator ScaleOverTime()
    {
        while (transform.localScale.x < targetScale.x && transform.localScale.y < targetScale.y && transform.localScale.z < targetScale.z && canChangeBig)
        {
            // 逐渐放大球体
            transform.localScale += originalScale * scaleSpeed * Time.deltaTime;
            yield return null; // 等待下一帧
        }
        //isScalingBig = false;
    }

    IEnumerator ScaleSmallTime()
    {
        while (transform.localScale.x > smallScale.x && transform.localScale.y > smallScale.y && transform.localScale.z > smallScale.z && canChangeSmall)
        {
            // 逐渐缩小球体
            transform.localScale -= originalScale * scaleSpeed * Time.deltaTime;
            yield return null; // 等待下一帧
        }
        //isScalingSmall = false;
    }
    IEnumerator ScaleHeat()
    {
        while (transform.localScale.x > originalScale.x && transform.localScale.y > originalScale.y && transform.localScale.z > originalScale.z && canChangeOri)
        {
            // 逐渐缩小球体
            transform.localScale -= originalScale * scaleSpeed * Time.deltaTime;
            yield return null; // 等待下一帧
        }
        //isScalingSmall = false;
        while (transform.localScale.x < originalScale.x && transform.localScale.y < originalScale.y && transform.localScale.z < originalScale.z && canChangeOri)
        {
            // 逐渐放大球体
            transform.localScale += originalScale * scaleSpeed * Time.deltaTime;
            yield return null; // 等待下一帧
        }
        //isScalingBig = false;
    }

    public void TakeDamage(float damage)
    {
        currentHealth -= damage;

        // 生命值不能小于0
        currentHealth = Mathf.Clamp(currentHealth, 0f, maxHealth);
    }
    void StartTakingDamage(float damage)
    {
        damageCooldown = 0f;  // 
        // 开始扣血
        StartCoroutine(TakeDamageOverTime(damage));
    }
    private System.Collections.IEnumerator TakeDamageOverTime(float damage)
    {
        float damagePerSecond = damage * Time.deltaTime; // 每秒扣除的伤害量（考虑帧间时间差）

        while (currentHealth > 0 && damageCooldown < 1f) // ֻҪ��������0�������۳�
        {
            currentHealth -= damagePerSecond * Time.deltaTime;
            currentHealth = Mathf.Clamp(currentHealth, 0f, maxHealth); // ȷ��������С�� 0
            damageCooldown += Time.deltaTime; // ����ʱ�������

            yield return null; // �ȴ���һ֡
        }
    }
    void RegenerateHealth()
    {
        // 恢复
        if (currentHealth < maxHealth)
        {
            currentHealth += healthRegenRate * Time.deltaTime; // ����ÿ��ָ������лָ�
            currentHealth = Mathf.Clamp(currentHealth, 0f, maxHealth); // ȷ���������������ֵ
        }
    }
    // �ָ������ĺ���
    public void Heal(float healing)
    {
        currentHealth += healing;

        // ȷ������ֵ���������ֵ
        currentHealth = Mathf.Clamp(currentHealth, 0f, maxHealth);
    }

    void MovePlayer()
    {
        float horizontal = Input.GetAxis("Horizontal");

        // �ƶ���ɫ��ˮƽ�ٶ�
        if (chongci)
        {
            Vector3 move = new Vector3(horizontal, 0, 0) * moveSpeed*5;
            move.y = rb.velocity.y; // ���ִ�ֱ�ٶȲ��䣬��ֹ������Ӱ����Ծʱ�ı��ٶ�
            rb.velocity = move;
        }
        else
        {
            Vector3 move = new Vector3(horizontal, 0, 0) * moveSpeed;
            move.y = rb.velocity.y; // ���ִ�ֱ�ٶȲ��䣬��ֹ������Ӱ����Ծʱ�ı��ٶ�
            rb.velocity = move;
        }
        moveDirection = new Vector2(horizontal, 0).normalized;

        // 计算鼠标位置
        Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        // 如果按下鼠标左键，则冲刺
        if (Input.GetMouseButtonDown(0) && !isDashing && canUP)
        {
            isDashing = true;
            TakeDamage(JumptakeDamage);
            StartCoroutine(ShowManCoroutine());
            
            dashDirection = (mousePosition - (Vector2)transform.position).normalized;
            dashTime = 0;
        }

        if(Input.GetKeyDown(KeyCode.Space))
        {
            rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse); // Ӧ���Զ�������
        }
        else
        {
            rb.AddForce( Vector2.up * gravity, ForceMode2D.Force); // Ӧ���Զ�������
            if(Mathf.Abs(rb.velocity.y) >= maxFallSpeed)
            {
                int dir = rb.velocity.y > 0 ? 1 : -1;
                rb.velocity = new Vector2(rb.velocity.x, dir * maxFallSpeed);
            }
        }


    }
    private IEnumerator ShowManCoroutine()
    {
        Image manImage = man.GetComponent<Image>(); // 获取man的Image组件
        manImage.enabled = true; // 启用Image组件
        Image kongImage = kong.GetComponent<Image>();
        kongImage.enabled = true;
        yield return new WaitForSeconds(0.5f); // 等待一秒
        manImage.enabled = false; // 禁用Image组件
        kongImage.enabled = false;
    }
    void ShowArrow()
    {
        // 显示箭头
        arrow.SetActive(true);

        // 获取鼠标在世界空间中的位置
        Vector3 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

        // 确保Z轴与起点相同（箭头不会在3D空间中偏移）
        mousePosition.z = startPoint.position.z;

        // 计算箭头的方向
        Vector2 direction = (mousePosition - startPoint.position).normalized;

        // 设置箭头的朝向，方向反转
        arrow.transform.up = -direction;  // 使用 -direction 来反转箭头朝向

        // 输出调试信息
        //Debug.Log("Arrow position: " + arrow.transform.position);
        //Debug.Log("Arrow direction: " + direction);

        // 启动定时器，几秒后隐藏箭头
        Invoke("HideArrow", displayTime);
    }

    void HideArrow()
    {
        // 隐藏箭头
        arrow.SetActive(false);
    }

    //应用重力
    void ApplyCustomGravity()
    {

        float maxSpeed = isScalingBig || isScalingSmall ? scalingMovingSpeed : maxFallSpeed;
        float dir = isScalingBig ? 1 : -1;
        if (Mathf.Abs(rb.velocity.y) <= maxSpeed)
        {
            rb.velocity = new Vector2(rb.velocity.x, dir * maxFallSpeed);
        }
        else
        {
            rb.AddForce(-dir * Vector2.up * gravity, ForceMode2D.Force); // Ӧ���Զ�������
        }
    }
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Barrier"))
        {
            GameManager.instance.FailGame();
            Debug.Log("死亡");
            //处理死亡逻辑

        }
    }
    
    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("UPUP"))
        {
            canStartUp = true;
        }
        if (collision.gameObject.CompareTag("ChangeBig"))
        {
            canChangeBig = true;
        }
        if (collision.gameObject.CompareTag("ChangeSmall"))
        {
            canChangeSmall = true;
        }
        if (collision.gameObject.CompareTag("ChangeBack"))
        {
            canChangeOri = true;
        }


    }
    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.gameObject.CompareTag("ChangeBig"))
        {
            canChangeBig = false;
        }
        if (collision.gameObject.CompareTag("ChangeSmall"))
        {
            canChangeSmall = false;
        }
        if (collision.gameObject.CompareTag("ChangeBack"))
        {
            canChangeOri = false;
        }
    }
    public float GetCurrentStaminaPercentage()
    {
        return currentHealth / maxHealth;
    }
    void OnGUI()
    {
        var style = new GUIStyle();
        style.fontSize = 32;
        GUI.Label(new Rect(0, 0, 140, 50), rb.velocity.ToString(), style);
    }
}
